﻿@using si.caha.Repository;
@using si.caha.Model;
@using si.caha.Helper;
@using System.Collections.Generic;
@using System.Linq;

@{
    /*
    Pseudocode Programming Process (PPP)
    
    We have many views in Store.cshtml page. 
    Items could be filtered by all of these parameters:
    - price
    - category
    - search
    - id (exceptional - just one result)

    All of others could be mixed together as:
    - search = "test" + price = 0 - 50  > /Store/Price?from=0&to=50&search=test
    - search = "test" + category = "Music" > /Store/Music/?search=test

    All of these except id could have also pageNumber parameter like so >  /Store/Music/?search=test&pageNumber=2
    */
    Layout = "/tpl/_layout.cshtml";
    PageData["PageTitle"] = "Store";
    DataContext dataContext = new DataContext();

    var pagnation = new Pagnation(10);
    
    var itemRepository = new ItemRepository(dataContext);
    var itemsToList = new List<Item>();

    var searchString = "";
    var isItemView = false;

    var filterFromUrl = UrlData.ToList();
    var filterFromUrlCount = filterFromUrl.Count;
    int idParameter = 0;

    if (filterFromUrlCount > 0)
    {
        idParameter = filterFromUrl.Last().IsInt() ? filterFromUrl.Last().AsInt() : 0;
        if(idParameter > 0 && filterFromUrlCount > 1)
        {
            isItemView = filterFromUrl.ElementAt(filterFromUrlCount - 2) == "Item";
        }
    }
    
    var noParameters = (Request["priceFrom"] == null && 
                        Request["priceTo"] == null && 
                        Request["search"] == null &&
                        filterFromUrl.Count == 0) ? true : false;
    // GET: /Store
    if (noParameters)
    {
        @ObjectInfo.Print("newest");
        itemsToList = itemRepository.GetNewest(pagnation.ItemsPerPage);
    }
    
    // GET: /Store/Category
    if (filterFromUrl.Count > 0 && !isItemView)
    {
        @ObjectInfo.Print("category");
        @ObjectInfo.Print(filterFromUrl.Last().Replace("-", " "));
        itemsToList = itemRepository.FilterByCategory(filterFromUrl.Last().Replace("-", " "));
    }
    
    // GET: /Store?priceFrom=10&priceTo=20
    if (Request["priceFrom"] != null && Request["priceTo"] != null)
    {
        @ObjectInfo.Print("price");
        int lowerPrice = Request["priceFrom"].AsInt();
        int upperPrice = Request["priceTo"].AsInt();
        
        if (itemsToList.Count == 0)
        {
            itemsToList = itemRepository.FilterByPrice(lowerPrice, upperPrice);
        }
        else
        {
            itemsToList = itemsToList.Where(i => i.Price <= upperPrice && i.Price >= lowerPrice).ToList();
        }
    }
        
    // GET: /Store?search=test
    if (Request["search"] != null && Request["search"].Length > 0 && !isItemView)
    {
        searchString = Request["search"];
        if (itemsToList.Count == 0 && filterFromUrl.Count == 0)
        {
            itemsToList = itemRepository.FindByTitleAndDescription(searchString);
            @ObjectInfo.Print("search without category > db query");
        }
        else
        {
            itemsToList = itemsToList.Where(i => i.Title.Contains(searchString)).ToList();
            itemsToList = itemsToList.Where(i => i.Description.Contains(searchString)).ToList();
            @ObjectInfo.Print("search with category > object filter = " + searchString);
        }
    }
    
    // must be exactly here before pageNumber request
    // because I have to get all itemsToList count to know where is the last next page link
    pagnation.ItemsCount = itemsToList.Count();
    @ObjectInfo.Print("itemsCount = " + itemsToList.Count());
    
    // GET: /Store?pageNumber=1
    if (Request["pageNumber"] != null)
    {
        pagnation.CurrentPageNumber = Request["pageNumber"].AsInt();
        @ObjectInfo.Print("pageNumber = " + pagnation.CurrentPageNumber);
        itemsToList = itemsToList.Skip((pagnation.CurrentPageNumber - 1) * pagnation.ItemsPerPage).Take(pagnation.ItemsPerPage).ToList();
    }
    
    // GET: /Store/Item/1
    if (isItemView)
    {
        @ObjectInfo.Print("isItemView");
        itemsToList.Clear();
        itemsToList.Add(itemRepository.Get(idParameter));
    }
    
    itemsToList = itemsToList.Take(pagnation.ItemsPerPage).ToList();
}
@if (!isItemView)
{
    <script>
        $(function(){
            // autocomplete with json
            $.getJSON("/partial/getAutocompleteList.cshtml",
                function(data){    
                    $("input#search").autocomplete({
                        source: data
                    });
            });
            
            $("#searchForm > #deleteSearchButton").hide();
            if ($("#searchForm > #search").val().length > 0) {
                $("#searchForm > #deleteSearchButton").show();
            }
            
            $("#searchForm > #deleteSearchButton").click(function(){
                $("#searchForm > #search").attr("value", "");
                window.location = "/Store";
            });
            
        });
    </script>

    <div>
        <form id="searchForm" method="get" action="@Request.Url.ToString().Replace(".cshtml", "")">
            <input type="search" id="search" name="search" value="@searchString" />
            <button type="submit" id="searchButton">Search for products</button>
            <button type="button" id="deleteSearchButton">Delete search</button>
        </form>
    </div>
}
@CategoryHierarchy.GetHtml(menuId: "treeView", rootTag: "nav")
<div>
    <p>Filter by price</p>
    <ul>
        <li><a href=@PriceFilter.RemoveFilterAndPagnation(Request.Url.ToString(), pagnation.CurrentPageNumber)>All prices</a></li>
        @foreach (var priceFilter in PriceFilter.GetPriceFilters())
        {
            <li><a href="@priceFilter.ToUrlString(Request.Url.ToString(), pagnation.CurrentPageNumber)">@priceFilter</a></li>
        }
    <ul>
</div>
<ul id="itemsList" class="itemsList">
@foreach (var item in itemsToList)
{
    var categories = CategoryHierarchy.GetCategorieshierarchyFromItem(item);
    if (!isItemView)
    {
        var frontImage = item.Images.SingleOrDefault(i => i.FrontImage);
        <li class="item">
            <a href="@Href("~/Store" + @categories + "/Item/" + @item.ItemId)">@item.Title</a>
            @if (frontImage != null)
            {
                <a id="itemImgA" href="@Href("~/Store" + @categories + "/Item/" + @item.ItemId)">
                    <img src="@Href(@frontImage.Path)" />
                </a>
            }
            <p>€@item.Price</p>
            @if (Roles.IsUserInRole("admin"))
            {
                <a href="@Href("~/Admin/Items/Edit/" + @item.ItemId)">Edit item</a>
            }
        </li>
    }
    else
    {
        <li class="itemDetails">
            @RenderPage("_itemDetails.cshtml", new {item = @item})
        </li>
    }
}
</ul>
<div id="pagnation">
    <a href=@pagnation.GetFirstPageNumberUrl(Request.Url.ToString())>@pagnation.FirstPageLink()</a>
    <a href=@pagnation.GetPreviousPageNumberUrl(Request.Url.ToString())>@pagnation.PreviousPageLink()</a>
    <span>Page: @pagnation.CurrentPageNumber of @pagnation.LastPage()</span>
    <a href=@pagnation.GetNextPageNumberUrl(Request.Url.ToString())>@pagnation.NextPageLink()</a>
    <a href=@pagnation.GetLastPageNumberUrl(Request.Url.ToString())>@pagnation.LastPageLink()</a>
</div>
